package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.fragment.producerFragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.util.Calendar;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import android.Manifest;
import android.content.pm.PackageManager;


import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.zxing.WriterException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.UUID;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.ActivityLogin;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Product;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Trace;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceConnection.LoginServiceConnection;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceConnection.ProductServiceConnection;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.LoginService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.ImageUtils;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.JSONObjectUtils;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.ProductUtils;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.QRCodeUtils;

public class FragmentAddProduct extends Fragment {
    String productId = UUID.randomUUID().toString();
    private ImageView productImageView, productQRView; // 产品照片, 产品QR
    private EditText mProductId, mProductName, mProductType, mProductPrice, mProductDate, mProductState;
    Button btnAddProduct; // 添加照片按钮，从图库中提交，提交田间产品按钮
    Bitmap qrCodeBitmap;
    private ActivityResultLauncher<Uri> takePhotoLauncher;
    private Uri photoUri;
    private ProductServiceConnection productConnection;
    private ImageUtils imageUtils;
    private QRCodeUtils qrCodeUtils = new QRCodeUtils();
    private ImageView iconAdd;

    private Button btnBatchImport; // 批量导入按钮
    private static final int PICK_TEXT_FILE = 3;
    private static final int PICK_EXCEL_FILE = 4;

    private static final int REQUEST_CAMERA_PERMISSION = 100;
    private static final int REQUEST_STORAGE_PERMISSION = 101;
    private FrameLayout imageFrame;

    public FragmentAddProduct(ProductServiceConnection productConnection) {
        this.productConnection = productConnection;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @SuppressLint("MissingInflatedId")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_product, container, false);
        setHasOptionsMenu(true);

        // 初始化视图组件
        mProductId = view.findViewById(R.id.product_id);
        mProductName = view.findViewById(R.id.product_name);
        mProductType = view.findViewById(R.id.product_type);
        mProductPrice = view.findViewById(R.id.product_price);
        mProductDate = view.findViewById(R.id.sale_date);
        mProductState = view.findViewById(R.id.product_status);
        productImageView = view.findViewById(R.id.product_image);
        productQRView = view.findViewById(R.id.product_QR);
        imageFrame = view.findViewById(R.id.image_frame);
        iconAdd = view.findViewById(R.id.icon_add);
        btnAddProduct = view.findViewById(R.id.btn_add_product);
        btnBatchImport = view.findViewById(R.id.btn_batch_import);

        btnBatchImport.setOnClickListener(v -> showBatchImportMenu());

        // 设置默认值
        mProductId.setText(productId);
        mProductId.setEnabled(false);
        mProductState.setText("待生产");
        mProductState.setEnabled(false);

        requestPermissions();

        // 生成二维码
        try {
            qrCodeBitmap = QRCodeUtils.generateQRCode(productId, 300, 300);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }
        productQRView.setImageBitmap(qrCodeBitmap);

        // 设置价格输入监听
        mProductPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.toString().matches("^\\d*(\\.\\d{0,2})?$")) {
                    String input = s.toString();
                    String filtered = input.replaceAll("[^\\d.]", ""); // 过滤非数字字符
                    if (filtered.contains(".")) {
                        filtered = filtered.substring(0, Math.min(filtered.indexOf('.') + 3, filtered.length())); // 限制小数位
                    }
                    mProductPrice.setText(filtered);
                    mProductPrice.setSelection(filtered.length()); // 保证光标位置正确
                }
            }
            @Override
            public void afterTextChanged(Editable s) {}
        });

        // 日期选择器
        mProductDate.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog datePickerDialog = new DatePickerDialog(this.requireContext(), (unusedView, selectedYear, selectedMonth, selectedDay) -> {
                String date = String.format(Locale.getDefault(), "%04d-%02d-%02d", selectedYear, selectedMonth + 1, selectedDay);
                mProductDate.setText(date);
            }, year, month, day);
            datePickerDialog.show();
        });


        imageFrame.setOnClickListener(v -> showImageSelectionMenu());
        btnAddProduct.setOnClickListener(v -> addProduct());

        // 初始化拍照功能
        initTakePhotoLauncher();

        return view;
    }

    private void showBatchImportMenu() {
        PopupMenu popupMenu = new PopupMenu(getActivity(), btnBatchImport);
        Menu menu = popupMenu.getMenu();
        menu.add(Menu.NONE, R.id.action_import_text, Menu.NONE, "从文本文件导入");
        menu.add(Menu.NONE, R.id.action_import_excel, Menu.NONE, "从Excel文件导入");

        popupMenu.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.action_import_text) {
                importTextFile();
                return true;
            } else if (itemId == R.id.action_import_excel) {
                importExcelFile();
                return true;
            }
            return false;
        });
        popupMenu.show();
    }

    private void showImageSelectionMenu() {
        String[] options = {"拍摄照片", "从图库选择"};
        new AlertDialog.Builder(requireContext())
                .setTitle("选择图片来源")
                .setItems(options, (dialog, which) -> {
                    if (which == 0) {
                        takePhoto(); // 拍照
                    } else if (which == 1) {
                        openImagePicker(); // 从图库选择
                    }
                })
                .show();
    }

    private void initTakePhotoLauncher() {
        takePhotoLauncher = registerForActivityResult(
                new ActivityResultContracts.TakePicture(),
                success -> {
                    if (success && photoUri != null) {
                        showPhoto(); // 在成功拍照后显示照片
                    } else {
                        Toast.makeText(getActivity(), "拍照失败", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    private void showPhoto() {
        if (photoUri != null) {
            try {
                // 从 Uri 创建输入流并解码 Bitmap
                InputStream inputStream = requireActivity().getContentResolver().openInputStream(photoUri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                if (bitmap != null) {
                    productImageView.setImageBitmap(bitmap);
                    productImageView.setVisibility(View.VISIBLE); // 显示 ImageView
                    iconAdd.setVisibility(View.GONE);
                } else {
                    Toast.makeText(getActivity(), "无法解码图片", Toast.LENGTH_SHORT).show();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "文件未找到", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void requestPermissions() {
        if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }

        if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CAMERA_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Camera permission granted
                    Toast.makeText(getActivity(), "相机权限已授予", Toast.LENGTH_SHORT).show();
                } else {
                    // Camera permission denied
                    Toast.makeText(getActivity(), "相机权限被拒绝", Toast.LENGTH_SHORT).show();
                }
                break;
            case REQUEST_STORAGE_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Storage permission granted
                    Toast.makeText(getActivity(), "存储权限已授予", Toast.LENGTH_SHORT).show();
                } else {
                    // Storage permission denied
                    Toast.makeText(getActivity(), "存储权限被拒绝", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void takePhoto() {
        // 确保在调用摄像头之前检查权限
        if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            // 创建临时文件的 URI
            File tempFile;
            try {
                // 创建用于存储照片的临时文件
                File storageDir = requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                tempFile = File.createTempFile("photo_", ".jpg", storageDir);
                photoUri = FileProvider.getUriForFile(
                        requireActivity(),
                        requireActivity().getPackageName() + ".fileprovider",
                        tempFile
                );
                takePhotoLauncher.launch(photoUri);
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "无法创建临时文件", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getActivity(), "请先授予相机权限", Toast.LENGTH_SHORT).show();
        }
    }

    private void addProduct() { //需要增加确认功能，因为照片不能更改
        String productName = mProductName.getText().toString();
        String productType = mProductType.getText().toString();
        String productPrice = mProductPrice.getText().toString();
        String productDate = mProductDate.getText().toString();

        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("ACCOUNT_REMEMBER", requireActivity().MODE_PRIVATE);
        Integer userId = sharedPreferences.getInt("userId", -1);
        Integer userRole = sharedPreferences.getInt("role", -1);
        Log.d("验证用户基本信息", userId + " " + userRole);

        // 用户验证
        if (userId == -1) {
            Toast.makeText(getActivity(), "非法登录！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), ActivityLogin.class);
            startActivity(intent);
            return;
        }
        if (productName.isEmpty() || productType.isEmpty() || productPrice.isEmpty() || productDate.isEmpty()) {
            Toast.makeText(getActivity(), "请完善产品信息！", Toast.LENGTH_SHORT).show();
            return;
        }

        Product product = new Product(productId, productName, ImageUtils.bitmap2Blob(qrCodeBitmap), productType, Double.parseDouble(productPrice), productDate, 0);
        Boolean addProductInfo = productConnection.getService().addProduct(product); // 添加产品信息
        Log.d("添加产品基本信息", "success1");

        // 添加关联信息（如果有图片）
        if (addProductInfo && productImageView.getDrawable() != null) {
            Trace trace = new Trace();
            Bitmap productImage = imageUtils.drawable2bitmap(productImageView.getDrawable());
            trace.setProductId(productId);
            trace.setProducerId(userId);
            trace.setProducerImg(imageUtils.bitmap2Blob(productImage));
            addProductInfo = productConnection.getService().addTraceabilityPicture(trace, 0);
            Log.d("添加产品额外信息", "success2" + addProductInfo);
        }

        Toast.makeText(getActivity(), "产品已添加！", Toast.LENGTH_SHORT).show(); // 提示用户产品已添加
    }

    // 图库选择
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*"); // 只显示图片类型的文件
        startActivityForResult(intent, 2); // 请求码为2
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            if (resultCode == getActivity().RESULT_OK && data != null) {
                Uri selectedImageUri = data.getData(); // 获取选中图片的URI
                productImageView.setImageURI(selectedImageUri);
                productImageView.setVisibility(View.VISIBLE); // 显示 ImageView
                iconAdd.setVisibility(View.GONE);
            }
        }
        else if (resultCode == getActivity().RESULT_OK && data != null) {
            Uri uri = data.getData();

            if (requestCode == PICK_TEXT_FILE) {
                // 处理文本文件导入
                List<Product> products = new ArrayList<>();
                try {
                    int errorLine = ProductUtils.importFromTextFile(products, getActivity().getContentResolver(), uri);
                    if (errorLine == -1) {
                        productConnection.getService().importProductsFromOtherFiles(products);
                        Toast.makeText(getActivity(), "导入成功！", Toast.LENGTH_SHORT).show();
                    } else {
                        // 处理错误行
                        Toast.makeText(getActivity(), "错误在第 " + errorLine + " 行", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "导入失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else if (requestCode == PICK_EXCEL_FILE) {
                // 处理 Excel 文件导入
                List<Product> products = new ArrayList<>();
                try {
                    int errorLine = ProductUtils.importFromExcelFile(products, getActivity().getContentResolver(), uri);
                    // 成功导入
                    // 处理 products 列表，例如添加到数据库
                    if (errorLine == -1) {
                        productConnection.getService().importProductsFromOtherFiles(products);
                        Toast.makeText(getActivity(), "导入成功！", Toast.LENGTH_SHORT).show();
                    } else {
                        // 处理错误行
                        Toast.makeText(getActivity(), "错误在第 " + errorLine + " 行", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "导入失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_menu, menu); // 加载你的菜单XML资源
    }

    private void importTextFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("text/plain");
        startActivityForResult(intent, PICK_TEXT_FILE);
    }

    private void importExcelFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        startActivityForResult(intent, PICK_EXCEL_FILE);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.action_import_text) {// 处理导入文本文件的逻辑
            importTextFile();
            return true;
        } else if (itemId == R.id.action_import_excel) {// 处理导入Excel文件的逻辑
            importExcelFile();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}